package com.jushu.storbox;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.actions.AlbumAction;
import com.jushu.storbox.actions.LogoutAction;
import com.jushu.storbox.callback.IOneboxLastDisTimerListener;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IAlbumDao;
import com.jushu.storbox.entities.AlbumFileInfo;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.fragment.AllFileFragment;
import com.jushu.storbox.fragment.BaseFragment;
import com.jushu.storbox.fragment.SettingFragment;
import com.jushu.storbox.fragment.ShareFragment;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.manager.UploadTaskManager;
import com.jushu.storbox.network.WifiController;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.task.tqueue.UploadTask;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.OneboxLastDisTimer;
import com.jushu.storbox.util.PublicTools;
import com.huawei.sharedrive.sdk.android.exception.ClientException;

/**
 * 
 * Cloud Drive Main Fragment Activity(FragmentActivity)
 * 
 */
public class ShareDriveMainFragmentActivity extends Activity{
	
	/** activity TAG */
	private final static String LOG_TAG = "ShareDriveMainFragmentActivity";

	/** define fragment */
	public AllFileFragment allFilePage;
	private ShareFragment sharePage;
	private SettingFragment settingPage;

	/** bottom button container */
	private FrameLayout myCloudDriveFragment;
	private FrameLayout sharedForMeFragment;
	private FrameLayout settintFragment;
	private FrameLayout translateFragment;

	/** bottom button icon */
	private ImageView myCloudDriveIcon;
	private ImageView shareForMeIcon;
	private ImageView settingIcon;
	private ImageView translateIcon;
	/** bottom button text */
	/** file content tv */
	private TextView myCloudDriveText;
	private TextView shareForMeText;
	private TextView settingText;
	private TextView translateText;
	/** two back key,time */
	private long mExitTime = 0l;

	/** fragment stack */
	private FragmentManager fragmentManager;

	/** Fragment basic class */
	private BaseFragment currentFragment;

	/** current fragment serialno */
	private int currentIndex = 0;

	/** fragment transaction */
	private FragmentTransaction transaction;

	/** shareDriveService  */
	public ICloudDriveService shareDriveService;

	/** more title button */
	private RelativeLayout filelist_tittle_more_top_img;

	/** fragment  */
	private int i_count;

	private boolean choice = false;
	private boolean isTransverseDir = false;

	private OneboxLastDisTimer lastDisTimer = new OneboxLastDisTimer(800, 800);

	private TextView main_tittle_te;
	private ProgressBar filelist_tittle_loading_re;

	private FrameLayout frame_tittle_search;
	private FrameLayout frame_tittle_all;
	private EditText search_et;
	private LinearLayout buttom_search_ll;
	private LinearLayout buttom_main_ll;
	private RelativeLayout main_search_confirm_rl;
	private RelativeLayout tittle_search_cancle_ll;
	private float s_y = 0f;
	private float s_x = 0f;
	private ImageView search_clear_icon;
	private Map<String, Object> moveViewMap;
	private int moveToRight;
	private Holder holder;
	private InputMethodManager inputManager;

	private TextWatcher searchWatcher;
	private OnClickListener searchConfimClickListener;
	private OnClickListener searchCleanClickListener;
	private OnClickListener searchCancelClickListener;
	private OnClickListener allFileClickListener;
	private OnClickListener shareClickListener;
	private OnClickListener settintClickListener;
	private OnClickListener translateClickListener;
	private OnClickListener titleMoreClickListener;

	public Map<String, Object> getMoveViewMap() {
		return moveViewMap;
	}

	public void setMoveViewMap() {
		Log.d("te003", "setMoveViewMap");
		BaseFragment cur_Bfg = null;
		BaseFragment pre_Bfg = null;
		Log.d("te003", "fragmentManager.getBackStackEntryCount():"
				+ fragmentManager.getBackStackEntryCount());
		Map<String, Object> moveViewMap = new HashMap<String, Object>();
		if (1 < fragmentManager.getBackStackEntryCount()) {
			pre_Bfg = (BaseFragment) fragmentManager.findFragmentByTag(i_count
					+ "");
			Log.d("te003", "pre_Bfg:" + pre_Bfg);
			if (null != pre_Bfg) {
				View pre = pre_Bfg.getConventview();
				moveViewMap.put("pre", pre);
			}
			cur_Bfg = (BaseFragment) fragmentManager
					.findFragmentByTag((i_count - 1) + "");
			if (null != cur_Bfg) {
				View cur = cur_Bfg.getConventview();
				moveViewMap.put("cur", cur);
				moveViewMap.put("curfg", cur_Bfg);
				LinearLayout shadowLayout = cur_Bfg.getShawodLayout();
				moveViewMap.put("layout", shadowLayout);
			} else {
				Log.d("setposi", "currentFg[0]:" + currentFragment);
				Log.d("setposi", "index[0]:" + i_count);
			}
		} else if (1 == fragmentManager.getBackStackEntryCount()) {
			pre_Bfg = (BaseFragment) fragmentManager.findFragmentByTag(i_count
					+ "");
			Log.d("te003", "pre_Bfg:" + pre_Bfg);
			if (null != pre_Bfg) {
				View pre = pre_Bfg.getConventview();
				moveViewMap.put("pre", pre);
			}
			View cur = null;
			// popBackStack(1, fragmentManager);
			switch (currentIndex) {
			case UiConstant.ALLFILEFRAGMENT:
				if (null != allFilePage) {
					cur = allFilePage.getConventview();
					moveViewMap.put("cur", cur);
					moveViewMap.put("curfg", allFilePage);
					LinearLayout shadowLayout = allFilePage.getShawodLayout();
					moveViewMap.put("layout", shadowLayout);
				}
				break;
			case UiConstant.SHAREFRAGMENT:
				if (null != sharePage) {
					cur = sharePage.getConventview();
					moveViewMap.put("curfg", sharePage);
					LinearLayout shadowLayout = sharePage.getShawodLayout();
					moveViewMap.put("layout", shadowLayout);
					moveViewMap.put("cur", cur);
				}
				break;

			default:
				break;
			}
		}
		this.moveViewMap = moveViewMap;
	}

	/***
	 * seervice connection
	 */
	public ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LogUtil.i(LOG_TAG, "onServiceConnected()");
			shareDriveService = ((CloudDriveService.CenterShareDriveServiceServiceBinder) service)
					.getService();
			if (null != shareDriveService) {
				Message msg = new Message();
				msg.what = UiConstant.ONCONNECTCOMPLETE;
				handler.sendMessageDelayed(msg, 200);
			} else {
				PublicTools.restartApp(ShareDriveMainFragmentActivity.this);
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			shareDriveService = null;
			LogUtil.e(LOG_TAG, "onServiceDisconnected()");
		}
	};

	protected void onSaveInstanceState(Bundle outState) {
		if (null == currentFragment) {
			PublicTools.restartApp(ShareDriveMainFragmentActivity.this);
		}
	};

	@Override
	protected void onResume() {
		LogUtil.i(LOG_TAG, "onResume()");
		if (null != shareDriveService) {
			shareDriveService.checkIsRootAndNotify();
		}
		super.onResume();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		LogUtil.i(LOG_TAG, "onStop()");
		super.onStop();
	}

	/**
	 * onCreate in ShareDriveMainFragmentActivity
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		LogUtil.i(LOG_TAG, "onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sharedrive_fragment_activity_main);
		ActivityTaskManager.getInstance().putActivity(LOG_TAG,
				ShareDriveMainFragmentActivity.this);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		bindservice();
		setupView();
		initdata();
		initlistenser();
		checkFixed();
		if(PublicTools.getAlbumBackup(ShareDriveMainFragmentActivity.this)){
			startAlbumBackup();
		}
		// DisplayMetrics dm = PublicTools
		// .getScreenWidthAndHeight(ShareDriveMainFragmentActivity.this);
		//
		// PublicTools.pxTodip(ShareDriveMainFragmentActivity.this,
		// dm.widthPixels);
	}

	public void checkFixed() {
		if (!PublicTools.checkIsFixed(
				ShareDriveMainFragmentActivity.this.getApplicationContext(),
				ClientConfig.ANYOFFICE_PACKAGE_NAME)) {
			SharedPreferences preferences = ShareDriveMainFragmentActivity.this
					.getSharedPreferences(ClientConfig.settings,
							Context.MODE_APPEND);
			if (!preferences.getBoolean(ClientConfig.NOT_NEED_NOTIFY, false)) {
				handler.sendEmptyMessage(UiConstant.NEED_NOTIFY_INSTALL_ANYOFFICE);
			}
		}
	}

	private void initdata() {
		// TODO Auto-generated method stub
		if (null == holder) {
			holder = new Holder();
		}
		if (null == inputManager) {
			inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		LogUtil.i(LOG_TAG, "onDestroy()");
		// TODO Auto-generated method stub
		if (null != shareDriveService) {
			SharedPreferences settings = getSharedPreferences(
					ClientConfig.settings, MODE_APPEND);
			Editor editor = settings.edit();
			// editor.putLong(ClientConfig.SAVEDTIME, 0l);
			editor.putBoolean(ClientConfig.LOGIN_BACKGROUND, false);
			editor.commit();
		}
		if (null != serviceConnection)
			unbindService(serviceConnection);
		ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
		handler = null;
		stopAlbumBackup();
		super.onDestroy();
	}

	private void setupView() {
		myCloudDriveFragment = (FrameLayout) findViewById(R.id.fragment_all_file_fl);
		sharedForMeFragment = (FrameLayout) findViewById(R.id.fragment_sharedrive_fl);
		settintFragment = (FrameLayout) findViewById(R.id.fragment_setting_fl);
		translateFragment = (FrameLayout) findViewById(R.id.fragment_translate_fl);
		myCloudDriveIcon = (ImageView) findViewById(R.id.fragment_all_file_im);
		shareForMeIcon = (ImageView) findViewById(R.id.fragment_sharedrive_im);
		settingIcon = (ImageView) findViewById(R.id.fragment_setting_im);
		translateIcon = (ImageView) findViewById(R.id.fragment_translate_im);
		myCloudDriveText = (TextView) findViewById(R.id.fragment_all_file_tx);
		shareForMeText = (TextView) findViewById(R.id.fragment_sharedrive_tv);
		settingText = (TextView) findViewById(R.id.fragment_setting_tv);
		translateText = (TextView) findViewById(R.id.fragment_translate_tv);
		filelist_tittle_more_top_img = (RelativeLayout) findViewById(R.id.filelist_tittle_more_top_img);

		main_tittle_te = (TextView) findViewById(R.id.main_tittle_te);
		filelist_tittle_loading_re = (ProgressBar) findViewById(R.id.filelist_tittle_loading_re);
		frame_tittle_search = (FrameLayout) findViewById(R.id.frame_tittle_search);
		frame_tittle_all = (FrameLayout) findViewById(R.id.frame_tittle_all);
		search_et = (EditText) findViewById(R.id.search_et);
		search_clear_icon = (ImageView) findViewById(R.id.search_clear_icon);
		buttom_search_ll = (LinearLayout) findViewById(R.id.buttom_search_ll);
		buttom_main_ll = (LinearLayout) findViewById(R.id.buttom_main_ll);
		main_search_confirm_rl = (RelativeLayout) findViewById(R.id.main_search_confirm_rl);
		tittle_search_cancle_ll = (RelativeLayout) findViewById(R.id.tittle_search_cancle_ll);
	}

	private void initlistenser() {
		searchWatcher = new TextWatcher() {
			@Override
			public void onTextChanged(final CharSequence arg0, int arg1,
					int arg2, int arg3) {
				if (currentFragment instanceof AllFileFragment) {
					holder.setSearchFg((AllFileFragment) currentFragment);
					if (View.VISIBLE == search_et.getVisibility()) {

						if (null != lastDisTimer) {
							IOneboxLastDisTimerListener callback = new IOneboxLastDisTimerListener() {
								@Override
								public void onFinish() {
									// TODO Auto-generated method stub
									holder.getSearchFg()
											.search(arg0.toString());
								}
							};
							lastDisTimer.setCallback(callback);
							lastDisTimer.restartTimer();
						}
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
			}
		};
		searchConfimClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (null != currentFragment
						&& currentFragment instanceof AllFileFragment) {
					if (!ShareDriveApplication.getInstance()
							.isFastDoubleClick()) {
						((AllFileFragment) currentFragment).search(search_et
								.getText().toString());
					}
				}
			}
		};
		searchCleanClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (View.VISIBLE == search_et.getVisibility()) {
					search_et.setText("");
				}
			}
		};
		searchCancelClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (null != currentFragment) {
					if (currentFragment instanceof AllFileFragment) {
						PublicTools.hideSoftInput(inputManager, search_et);
						handler.sendEmptyMessage(UiConstant.HIDE_SEARCH_BAR);
					} else {
						setTabSelection(currentIndex);
					}
				}
			}
		};
		allFileClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {// display all fragment
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {

					if (!holder.animIsRunning) {
						if (currentFragment.getCanBack()) {
							if (null != filelist_tittle_more_top_img) {
								filelist_tittle_more_top_img
										.setVisibility(View.VISIBLE);
							}
							setTabSelection(UiConstant.ALLFILEFRAGMENT);
							if (UiConstant.DIR_CODE_1001 == currentFragment.getDir()) {
								changeTittle(currentFragment.getParent());

								currentFragment.setDir(UiConstant.DIR_CODE_25);
							}
						}
					}
				}
			}
		};
		shareClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
					if (!holder.animIsRunning) {
						if (currentFragment.getCanBack()) {
							if (null != filelist_tittle_more_top_img) {
								filelist_tittle_more_top_img
										.setVisibility(View.GONE);
							}
							setTabSelection(UiConstant.SHAREFRAGMENT);
						}
					}
				}
			}
		};
		settintClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
					if (!holder.animIsRunning) {
						if (currentFragment.getCanBack()) {
							if (null != filelist_tittle_more_top_img) {
								filelist_tittle_more_top_img
										.setVisibility(View.GONE);
							}
							setTabSelection(UiConstant.SETTINGFRAGMENT);
						}
					}
				}
			}
		};
		translateClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
					if (!holder.animIsRunning) {
						if (currentFragment.getCanBack()) {
//							setTabSelection(AllFileFragementContant.DOWNLOADFRAGMENT);
						}
					}
				}
			}
		};
		titleMoreClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
					if (!holder.animIsRunning) {
						if (null != currentFragment) {
							if (currentFragment instanceof AllFileFragment) {
									LinearLayout loadingLayout = ((AllFileFragment) currentFragment)
											.getLoadingView();
	
									if (View.GONE == filelist_tittle_loading_re
											.getVisibility()) {
										if (null != loadingLayout
												&& View.GONE == loadingLayout
														.getVisibility()) {
											((AllFileFragment) currentFragment)
													.initMenuDialog();
										}
									}
								
							}
						} else {
							LogUtil.e(LOG_TAG, "all file fragment is null");
						}
					}
				}
			}
		};
		
		//binding listener
		search_clear_icon.setOnClickListener(searchCleanClickListener);
		myCloudDriveFragment.setOnClickListener(allFileClickListener);
		sharedForMeFragment.setOnClickListener(shareClickListener);
		settintFragment.setOnClickListener(settintClickListener);
		translateFragment.setOnClickListener(translateClickListener);
		filelist_tittle_more_top_img.setOnClickListener(titleMoreClickListener);
		main_search_confirm_rl.setOnClickListener(searchConfimClickListener);
		tittle_search_cancle_ll.setOnClickListener(searchCancelClickListener);
		
		search_et.addTextChangedListener(searchWatcher);
	}
	
	private void bindservice() {
		Intent intent = new Intent(ShareDriveMainFragmentActivity.this,
				CloudDriveService.class);
		intent.setAction("tokenAlarm");
		if (null != serviceConnection) {
			bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
		}
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		if (null == currentFragment) {
			PublicTools.restartApp(ShareDriveMainFragmentActivity.this);
		}
		LogUtil.i(LOG_TAG, "onConfigurationChanged");
		super.onConfigurationChanged(newConfig);
	}

	private void resetTextColorToGray(){
		myCloudDriveText.setTextColor(this.getResources().getColor(
				R.color.gray));
		shareForMeText.setTextColor(this.getResources().getColor(
				R.color.gray));
		settingText
				.setTextColor(this.getResources().getColor(R.color.gray));
		translateText.setTextColor(this.getResources().getColor(
				R.color.gray));
	}
	
	private void setTabSelection(int index) {
		/** clear stack */ 
		if(ShareDriveMainFragmentActivity.this == null){
			return;
		}
		if (null == fragmentManager) {
			fragmentManager = getFragmentManager();
		}
		fragmentManager.popBackStack(null,
				FragmentManager.POP_BACK_STACK_INCLUSIVE);
		/** stack serialno to 0 */
		i_count = 0;
		// clear selected state
		clearSelection();
		// bengin Fragment transaction
		transaction = fragmentManager.beginTransaction();
		// hide all fragment.
		hideFragments(transaction);
		if (index != currentIndex) {
			stopFragments(currentFragment);
		}
		currentIndex = index;
		resetTextColorToGray();
		switch (index) {
			case UiConstant.ALLFILEFRAGMENT:
				showAllFileFragment();
				break;
				
			case UiConstant.SHAREFRAGMENT:
				showShareFragment();
				break;
				
			case UiConstant.SETTINGFRAGMENT:
				showSettingFragment();
				break;
				
		}
		transaction.commit();
	}

	private void showAllFileFragment() {
		changeTittle(getString(R.string.my_cloud_drive));
		showMoreUI();
		showTitleUI();
		myCloudDriveText.setTextColor(this.getResources().getColor(
				R.color.blue));
		myCloudDriveFragment.setSelected(true);
		myCloudDriveIcon.setSelected(true);
		if (null == allFilePage) {
			showProgressBar();
			allFilePage = new AllFileFragment();
			transaction.add(R.id.frame_content, allFilePage);
		} else {
			transaction.show(allFilePage);
			startFragments(allFilePage);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("service", shareDriveService);
		map.put("activityhandler", handler);
		map.put("all_entity", null);
		allFilePage.setObj(map);
		currentFragment = allFilePage;
		if (allFilePage.getDir() == UiConstant.DIR_CODE_1) {
			handler.sendEmptyMessageDelayed(14, 310);
		}
	}
	
	private void showShareFragment() {
		changeTittle(getString(R.string.nav_save_txt));
		hideMoreUI();
		showTitleUI();
		shareForMeText.setTextColor(this.getResources().getColor(
				R.color.blue));
		sharedForMeFragment.setSelected(true);
		shareForMeIcon.setSelected(true);
		if (sharePage == null) {
			showProgressBar();
			sharePage = new ShareFragment();
			transaction.add(R.id.frame_content, sharePage);
		} else {
			transaction.show(sharePage);
			startFragments(sharePage);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("service", shareDriveService);
		map.put("activityhandler", handler);
		map.put("share_entity", null);
		sharePage.setObj(map);
		currentFragment = sharePage;
	}
	
	private void showSettingFragment() {
		changeTittle(getString(R.string.setting));
		hideMoreUI();
		showTitleUI();
		settingText.setTextColor(this.getResources().getColor(R.color.blue));
		settintFragment.setSelected(true);
		settintFragment.setSelected(true);
		settingIcon.setSelected(true);
		if (settingPage == null) {
			settingPage = new SettingFragment();
			transaction.add(R.id.frame_content, settingPage);
		} else {
			transaction.show(settingPage);
			startFragments(settingPage);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("service", shareDriveService);
		map.put("activityhandler", handler);
		settingPage.setObj(map);
		currentFragment = settingPage;
	}
	
	private void clearSelection() {
		LogUtil.i(LOG_TAG, "clearSelection()");
		sharedForMeFragment.setSelected(false);
		shareForMeIcon.setSelected(false);
		myCloudDriveFragment.setSelected(false);
		myCloudDriveIcon.setSelected(false);
		settintFragment.setSelected(false);
		settingIcon.setSelected(false);
		translateFragment.setSelected(false);
		translateIcon.setSelected(false);
	}

	/**
	 * @param transaction
	 */
	private void hideFragments(FragmentTransaction transaction) {
		LogUtil.i(LOG_TAG, "hideFragments()");
		if (allFilePage != null) {
			transaction.hide(allFilePage);
		}
		if (sharePage != null) {
			transaction.hide(sharePage);
		}
		if (settingPage != null) {
			transaction.hide(settingPage);
		}
	}

	private void stopFragments(Fragment currentFragment) {
		LogUtil.i(LOG_TAG, "stopFragments");
		if (currentFragment != null) {
			currentFragment.onPause();
			currentFragment.onStop();
		}
	}

	private void startFragments(Fragment currentFragment) {
		LogUtil.i(LOG_TAG, "startFragments");
		if (currentFragment != null) {
			currentFragment.onStart();
			currentFragment.onResume();
		}
	}

	/**
	 * ShareDriveMainFragmentActivity on key down
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (ShareDriveApplication.getInstance().isAnimShowing()) {
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long currentMills = System.currentTimeMillis();
			if (1000 < currentMills - holder.recordMills) {
				holder.setIslocked(true);
			} else {
				holder.setIslocked(false);
			}
			Log.d("lock002", "isLocked:" + holder.isIslocked());
			if (holder.isIslocked()) {
				LogUtil.i(LOG_TAG, "KEYCODE_BACK");
				if (null != currentFragment && currentFragment.getCanBack()) {
					LogUtil.i(LOG_TAG, "BackStackEntryCount:[onKeyDown]:"
							+ fragmentManager.getBackStackEntryCount());
					if (0 == currentIndex) {
						showMoreUI();
					} else {
						hideMoreUI();
					}
					if (1 < fragmentManager.getBackStackEntryCount()) {

						// fragmentManager.popBackStack();
						//
						// i_count -= 1;
						// currentFragment = (BaseFragment) fragmentManager
						// .findFragmentByTag(i_count + "");
						// changeTittle(currentFragment.getParent(),
						// currentFragment.getDir());
						popBackStack(0, fragmentManager);
						return true;
					} else if (1 == fragmentManager.getBackStackEntryCount()) {
						i_count = 0;
						popBackStack(1, fragmentManager);
						switch (currentIndex) {
						case UiConstant.ALLFILEFRAGMENT:
							setTabSelection(UiConstant.ALLFILEFRAGMENT);
							break;
						case UiConstant.SHAREFRAGMENT:
							setTabSelection(UiConstant.SHAREFRAGMENT);
							break;
						default:
							setTabSelection(UiConstant.ALLFILEFRAGMENT);
							break;
						}
						return true;
					} else {
						if (keyCode == KeyEvent.KEYCODE_BACK
								&& event.getRepeatCount() == 0) {
							isTransverseDir = false;
							long currentTime = System.currentTimeMillis();
							if (currentTime - mExitTime > 2000) {
								mExitTime = currentTime;
								Toast.makeText(
										ShareDriveMainFragmentActivity.this,
										R.string.main_fragment,
										Toast.LENGTH_SHORT).show();
							} else {
								new Thread(new Runnable()
			                    {
			                        @Override
			                        public void run()
			                        {
			                            
			                        	if (shareDriveService != null)
			                            {
			                                try
			                                {
			                                    shareDriveService.logout();
			                                }
			                                catch (ClientException e)
			                                {
			                                    // TODO Auto-generated catch block
			                                    LogUtil.e(LOG_TAG, "statueCode:" + e.getStatusCode());
			                                    e.printStackTrace();
			                                }
			                            }
			                        }
			                    }).start();
								stopAlbumBackup();
								new LogoutAction(ShareDriveMainFragmentActivity.this).logout(ShareDriveMainFragmentActivity.this);
							}
							return false;
						}
					}
					return super.onKeyDown(keyCode, event);
				}

			} else {
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(ShareDriveMainFragmentActivity.this == null 
					|| ShareDriveMainFragmentActivity.this.isFinishing()){
				LogUtil.i(LOG_TAG, "Current Activity has been destory!");
				return;
			}
			BaseFragment fg = null;
			FileFolderInfo infors = null;
			transaction = null;
			Map<String, Object> map = new HashMap<String, Object>();
			switch (msg.what) {
			case UiConstant.ALLFILEFRAGMENT:
				if (null == currentFragment) {
					return;
				}
				if (null != currentFragment.getConventview()) {
					if (0.0f != currentFragment.getConventview().getX()) {
						break;
					}
				}
				if (View.VISIBLE == search_et.getVisibility()) {
					search_et.setVisibility(View.GONE);
				}
				holder.recordMills = System.currentTimeMillis();
				showProgressBar();
				i_count += 1;
				fg = new AllFileFragment();
				if (null != msg.obj) {
					infors = (FileFolderInfo) msg.obj;
					infors = DAOFactory
							.instance(ShareDriveMainFragmentActivity.this)
							.getFolderDao().getFolderById(infors);
					if (null != infors) {
						changeTittle(infors.getName());
					} else {
						changeTittle(getString(R.string.my_cloud_drive));
					}

				} else {
					changeTittle(getString(R.string.my_cloud_drive));
				}
				map.put("service", shareDriveService);
				map.put("activityhandler", handler);
				map.put("all_entity", infors);
				map.put("dir", msg.arg1);
				fg.setObj(map);
				stopFragments(currentFragment);
				currentIndex = UiConstant.ALLFILEFRAGMENT;
				transaction = fragmentManager.beginTransaction();
				transaction.setCustomAnimations(
						R.animator.fragment_slide_left_enter,
						R.animator.fragment_slide_left_exit);

				// transaction.hide(currentFragment);
				transaction.addToBackStack(null);
				transaction.add(R.id.frame_content, fg, i_count + "");
				transaction.commit();
				currentFragment = fg;
				Log.e("anim0012",
						"Allfile:"
								+ fragmentManager.findFragmentByTag(i_count
										+ ""));
				break;
			case UiConstant.SHAREFRAGMENT:
				holder.recordMills = System.currentTimeMillis();
				showProgressBar();
				i_count += 1;
				fg = new ShareFragment();
				if (null != msg.obj) {
					infors = (FileFolderInfo) msg.obj;
					if (null != infors) {
						changeTittle(infors.getName());
					} else {
						changeTittle(getString(R.string.nav_save_txt));
					}

				} else {
					changeTittle(getString(R.string.nav_save_txt));
				}
				map.put("service", shareDriveService);
				map.put("activityhandler", handler);
				map.put("share_entity", infors);
				fg.setObj(map);
				stopFragments(currentFragment);
				currentIndex = UiConstant.SHAREFRAGMENT;
				transaction = fragmentManager.beginTransaction();
				transaction.setCustomAnimations(
						R.animator.fragment_slide_left_enter,
						R.animator.fragment_slide_left_exit);
				// transaction.hide(currentFragment);
				transaction.addToBackStack(null);
				transaction.add(R.id.frame_content, fg, i_count + "");
				transaction.commit();
				currentFragment = fg;
				Log.e("anim0012",
						":" + fragmentManager.findFragmentByTag(i_count + ""));
				break;
				
			case UiConstant.SUCCESS_GET_SERVER_FOLDER_INFOMATION:
				FileFolderInfo fileFolderInfo = (FileFolderInfo) msg.obj;
				String name = fileFolderInfo.getName();
				main_tittle_te.setText(name);
				break;
				
			case UiConstant.CLEAN_LOCAL_CACHE://11 Clear local cache
				if (null != allFilePage) {
					allFilePage.refreshFileListUI();
				}
				if (null != sharePage) {
					sharePage.refreshFileListUI();
				}
				setTabSelection(UiConstant.SETTINGFRAGMENT);
				break;
			case UiConstant.ONCONNECTCOMPLETE:
				if (null != shareDriveService) {
					fragmentManager = getFragmentManager();
					/** set default fragment */
					setTabSelection(UiConstant.ALLFILEFRAGMENT);
				}
				/**12 data load finish, loading hide */
			case UiConstant.HIDE_TOP_PROGRESSBAR:// top progressBar disappear
				if (1 == msg.arg1) {
					dissMissProgressBar();
				}
				PublicTools.hideSoftInput(inputManager, search_et);
			case UiConstant.HIDE_SEARCH_BAR://hide search bar
				PublicTools.hideSoftInput(inputManager, search_et);
				searchDismiss();
				break;
			case UiConstant.SHOW_SEARCH_BAR://14 display search bar
				searchShow();
				break;
			case UiConstant.NEED_NOTIFY_INSTALL_ANYOFFICE:
//				Dialog dialog = CloudDriveDialogUtil
//						.getFixAnyofficeDialog(ShareDriveMainFragmentActivity.this
//								.getApplicationContext());
//				dialog.show();
				break;
			case UiConstant.ON_ANIMATION_END:
				if (ShareDriveApplication.getInstance().isAnimShowing()) {
					ShareDriveApplication.getInstance().setAnimIsShowing(false);
				}
				break;
			default:
				break;
			}
		};
	};

	private void showTitleUI() {
		if (View.GONE == main_tittle_te.getVisibility()) {
			main_tittle_te.setVisibility(View.VISIBLE);
		}
	}

	private void hideTitleUI() {
		if (View.VISIBLE == main_tittle_te.getVisibility()) {
			main_tittle_te.setVisibility(View.GONE);
		}
	}

	private void showMoreUI() {
		if (View.GONE == filelist_tittle_more_top_img.getVisibility()) {
			filelist_tittle_more_top_img.setVisibility(View.VISIBLE);
		}
	}

	private void hideMoreUI() {
		if (View.VISIBLE == filelist_tittle_more_top_img.getVisibility()) {
			filelist_tittle_more_top_img.setVisibility(View.GONE);
		}
	}

	private void changeTittle(String tittleName) {
		if (View.VISIBLE == frame_tittle_search.getVisibility()) {
			frame_tittle_search.setVisibility(View.GONE);
			if (View.GONE == frame_tittle_all.getVisibility()) {
				frame_tittle_all.setVisibility(View.VISIBLE);
			}
			if (View.VISIBLE == buttom_search_ll.getVisibility()) {
				buttom_search_ll.setVisibility(View.GONE);
			}
			if (View.GONE == buttom_main_ll.getVisibility()) {
				buttom_main_ll.setVisibility(View.VISIBLE);
			}
		}
		if (null != tittleName && 0 != tittleName.length()) {
			main_tittle_te.setText(tittleName);
		}
	}

	private void showProgressBar() {
		if (View.GONE == filelist_tittle_loading_re.getVisibility()) {
			filelist_tittle_loading_re.setVisibility(View.VISIBLE);
		}
	}

	private void dissMissProgressBar() {
		if (View.VISIBLE == filelist_tittle_loading_re.getVisibility()) {
			filelist_tittle_loading_re.setVisibility(View.GONE);
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		float e_y = 0f;
		float e_x = 0f;
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			moveToRight = 0;
			if (holder.animIsRunning) {
				choice = false;
			} else {
				choice = true;
			}
			Log.d("moveAction", "choice[ACTION_DOWN]:" + choice);
			s_y = ev.getY();
			s_x = ev.getX();
			ShareDriveApplication.getInstance().setCanMove(false);
			holder.oldMills = System.currentTimeMillis();
			ShareDriveApplication.getInstance().setScrolling(false);
			break;
		case MotionEvent.ACTION_CANCEL:
			if (isTransverseDir) {
				onBackToParent(e_x - s_x);
			}
			ShareDriveApplication.getInstance().setCanMove(true);
			s_y = e_y;
			s_x = e_x;
			isTransverseDir = false;
			choice = false;
			moveToRight = 0;
			break;
		case MotionEvent.ACTION_OUTSIDE:
			Log.d("name001", "ACTION_OUTSIDE");
			break;
		case MotionEvent.ACTION_UP:
			DisplayMetrics dm = PublicTools
					.getScreenWidthAndHeight(ShareDriveMainFragmentActivity.this);
			int scr_w = dm.widthPixels;
			;
			if (isTransverseDir) {
				onBackToParent(e_x - s_x);
			}
			Log.d("w001", "scr_w / 2:" + scr_w / 2);
			Log.d("w001", "e_x - s_x:" + (e_x - s_x));
			ShareDriveApplication.getInstance().setCanMove(false);
			s_y = e_y;
			s_x = e_x;
			isTransverseDir = false;
			choice = false;
			moveToRight = 0;
			break;
		case MotionEvent.ACTION_MOVE:
			if (View.VISIBLE == filelist_tittle_loading_re.getVisibility()) {
				choice = false;
				isTransverseDir = false;
			}
			if (currentFragment instanceof AllFileFragment
					|| currentFragment instanceof ShareFragment) {
				e_y = ev.getY();
				e_x = ev.getX();
				Log.d("moveAction", "choice[ACTION_MOVE_before]:" + choice);
				if (50 <= e_x - s_x) {
					ShareDriveApplication.getInstance().setScrolling(true);
				} else {
					ShareDriveApplication.getInstance().setScrolling(false);
				}
				Log.d("choi:", "choice | isTransverseDir:" + choice + "|"
						+ isTransverseDir);
				if (choice) {
					if (0 < e_x - s_x) {
						moveToRight = 1;// right
					} else {
						moveToRight = 2;// left
					}
					if (1 == moveToRight) {
						if (Math.abs((e_x - s_x)) >= Math.abs((e_y - s_y))) {
							isTransverseDir = true;
							setMoveViewMap();
						}
					} else if (2 == moveToRight) {
						if (Math.abs((e_x - s_x)) >= Math.abs((e_y - s_y))) {
							ShareDriveApplication.getInstance().setScrolling(
									true);
							// return true;
						}
					}
					Log.e("time001", "time:"
							+ (System.currentTimeMillis() - holder.oldMills)
							+ "|" + holder.oldMills);
					if (100 <= System.currentTimeMillis() - holder.oldMills) {
						choice = false;
					}
				}
				Log.d("moveAction", "choice[ACTION_MOVE_after]:" + choice);
				Log.e("moveAction", "isTransverseDir[ACTION_MOVE]:"
						+ isTransverseDir);
				if (isTransverseDir) {

					Log.d("tag_move", "back to parent folder");
					// setPosition((int)(e_x - s_x), currentIndex);
					setPosition((int) (e_x - s_x));
					return true;
				} else {
					Log.d("tag_move", "event to sub element");
				}
				Log.d("tag_move", "*x:" + (e_x - s_x));
				Log.d("tag_move", "*y:" + (e_y - s_y));
				if ((int) (e_y - s_y) >= 5) {
					if (null != currentFragment) {

						if (currentFragment instanceof AllFileFragment) {
							if (null != ((AllFileFragment) currentFragment)
									.getMyScrollView()
									&& 0 == ((AllFileFragment) currentFragment)
											.getMyScrollView().getScrollY()) {
								// if (0 >= buttom || buttom <= 136) {
								// n += (int) (e_y - s_y);
								// ps.setMargin(+ps.getElastic().dip2px(
								// ShareDriveMainFragmentActivity.this, 45)
								// - ps.getElastic().getElasticHeight());
								// }
								ShareDriveApplication.getInstance()
										.setScrolling(true);
								ShareDriveApplication.getInstance().setCanMove(
										true);
							}
						} else if (currentFragment instanceof ShareFragment) {
							if (null != ((ShareFragment) currentFragment)
									.getShareScrollView()
									&& 0 == ((ShareFragment) currentFragment)
											.getShareScrollView().getScrollY()) {
								// if (0 >= buttom || buttom <= 136) {
								// n += (int) (e_y - s_y);
								// ps.setMargin(+ps.getElastic().dip2px(
								// ShareDriveMainFragmentActivity.this, 45)
								// - ps.getElastic().getElasticHeight());
								// }
								ShareDriveApplication.getInstance()
										.setScrolling(true);
								ShareDriveApplication.getInstance().setCanMove(
										true);
							}
						}
					}

				} else {
					// getElastic().dip2px(activity, 45)
					// if (buttom >= 0) {
					// n += (int) (e_y - s_y);
					// ps.setMargin(n
					// / 2
					// - ps.getElastic().getElasticHeight()
					// + ps.getElastic()
					// .dip2px(ShareDriveMainFragmentActivity.this,
					// 45));
					// }
					ShareDriveApplication.getInstance().setScrolling(false);
					ShareDriveApplication.getInstance().setCanMove(false);
				}
			}
			break;

		default:
			break;
		}
		return super.dispatchTouchEvent(ev);
	}

	private void popBackStack(int count, final FragmentManager fragmentManager) {
		if (null != fragmentManager) {
			Log.d("anim0012",
					"count[switch]:" + fragmentManager.getBackStackEntryCount());
			switch (count) {
			case 0:// count > 1
				final View pre = currentFragment.getConventview();
				i_count -= 1;
				fragmentManager.popBackStack();
				currentFragment = (BaseFragment) fragmentManager
						.findFragmentByTag(i_count + "");
				Log.e("anim0012",
						"[onkey]:"
								+ fragmentManager.findFragmentByTag(i_count
										+ ""));
				if(null == currentFragment || null == currentFragment.getConventview()){
					return;
				}
				final View current = currentFragment.getConventview();
				Log.d("anim0012", "pres[0]:" + pre);
				Log.d("anim0012", "currents[0]:" + current);
				Log.d("anim0012", "getParent[0]:" + currentFragment.getParent());
				changeTittle(currentFragment.getParent());
				final Animation in_anim = AnimationUtils.loadAnimation(
						ShareDriveMainFragmentActivity.this, R.anim.left_in);
				final Animation out_anim = AnimationUtils.loadAnimation(
						ShareDriveMainFragmentActivity.this, R.anim.right_out);
				out_anim.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation arg0) {
						// TODO Auto-generated method stub
						current.startAnimation(in_anim);
						if (!ShareDriveApplication.getInstance()
								.isAnimShowing()) {
							ShareDriveApplication.getInstance()
									.setAnimIsShowing(true);
						}
					}

					@Override
					public void onAnimationRepeat(Animation arg0) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationEnd(Animation arg0) {
						// TODO Auto-generated method stub
						ShareDriveApplication.getInstance().setScrolling(false);
						if (UiConstant.DIR_CODE_1 == currentFragment.getDir()) {
							handler.sendEmptyMessageDelayed(14, 310);
						} else {
							handler.sendEmptyMessageDelayed(13, 310);
						}
						handler.sendEmptyMessageDelayed(UiConstant.ON_ANIMATION_END, 500);
					}
				});
				pre.startAnimation(out_anim);
				break;
			case 1:// count == 1

				if (null == currentFragment || null == currentFragment.getConventview()) {
					return;
				}
				final View pres = currentFragment.getConventview();
				View currents = null;
				if (currentIndex == 0) {
					currents = allFilePage.getConventview();
				} else if (currentIndex == 1) {
					currents = sharePage.getConventview();
				}
				Log.d("anim0012", "pres:" + pres);
				Log.d("anim0012", "currents:" + currents);
				final View finalCurrents = currents;
				changeTittle(currentFragment.getParent());
				final Animation in_anims = AnimationUtils.loadAnimation(
						ShareDriveMainFragmentActivity.this, R.anim.left_in);
				final Animation out_anims = AnimationUtils.loadAnimation(
						ShareDriveMainFragmentActivity.this, R.anim.right_out);
				out_anims.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation arg0) {
						// TODO Auto-generated method stub
						finalCurrents.startAnimation(in_anims);
						if (!ShareDriveApplication.getInstance()
								.isAnimShowing()) {
							ShareDriveApplication.getInstance()
									.setAnimIsShowing(true);
						}
					}

					@Override
					public void onAnimationRepeat(Animation arg0) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationEnd(Animation arg0) {
						// TODO Auto-generated method stub
						ShareDriveApplication.getInstance().setScrolling(false);
						handler.sendEmptyMessageDelayed(UiConstant.ON_ANIMATION_END, 500);
					}
				});
				pres.startAnimation(out_anims);
				break;
			case 2:

				break;

			default:
				break;
			}
		}
	};

	private void setPosition(int psx) {
		if (0 < psx) {
			View cur = (View) getMoveViewMap().get("cur");
			View pre = (View) getMoveViewMap().get("pre");
			LinearLayout layout = (LinearLayout) getMoveViewMap().get("layout");
			int scr_w = PublicTools
					.getScreenWidthAndHeight(ShareDriveMainFragmentActivity.this).widthPixels;
			float src_wf = 1.0f * scr_w;
			float per = Math.abs(psx / src_wf);
			Log.d("w001", "per:" + per);
			int t1 = 3;
			float t2 = 2.0f;
			Log.d("w001", "tf:" + t1 / t2);
			Log.d("w001", "per:" + per);
			if (null != cur && null != pre && null != layout) {
				if (!ShareDriveApplication.getInstance().isAnimShowing()) {
					ShareDriveApplication.getInstance().setAnimIsShowing(true);
				}
				if (View.VISIBLE == search_et.getVisibility()) {
					search_et.setVisibility(View.GONE);
				}
				ShareDriveApplication.getInstance().setScrolling(true);
				holder.animIsRunning = true;
				layout.setVisibility(View.VISIBLE);
				pre.setX(psx);
				// cur.setX(-500 + psx / 2);
				layout.setAlpha(1.0f - per);
				holder.setPer(1.0f - per);
				Log.d("perss", "0.7f - per[setPosition]:" + (0.7f - per));
				Log.d("perss",
						"holder.getPer()[setPosition]:" + holder.getPer());
				cur.setX((psx - scr_w) / 2);
			}

		}
	}

	private void onBackToParent(float x) {
		final View cur = (View) getMoveViewMap().get("cur");
		View pre = (View) getMoveViewMap().get("pre");
		DisplayMetrics dm = PublicTools
				.getScreenWidthAndHeight(ShareDriveMainFragmentActivity.this);
		int scr_w = dm.widthPixels;
		final LinearLayout layout = (LinearLayout) getMoveViewMap().get(
				"layout");
		if (null != pre && null != cur && null != layout) {
			Log.d("w001",
					"3 * Math.abs(pre.getX()):" + 3 * Math.abs(pre.getX()));
			Log.d("w001", "scr_w:" + scr_w);
			if (3 * Math.abs(pre.getX()) <= scr_w) {
				cancleOnBackToParent(x);
				return;
			}
			float pre_x = x;
			final float finalScr_w = scr_w;
			final View final_Pre = pre;
			//
			TranslateAnimation cur_Ta = new TranslateAnimation(cur.getX(), 0,
					0, 0);
			cur_Ta.setDuration(250);
			cur_Ta.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation arg0) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation arg0) {
					// TODO Auto-generated method stub

				}
			});

			TranslateAnimation pre_Ta = new TranslateAnimation(pre.getX(),
					scr_w, 0, 0);

			pre_Ta.setDuration(250);
			pre_Ta.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation arg0) {
					// TODO Auto-generated method stub
					// holder.animIsRunning = true;
					onBackToParentStart();
					if (!ShareDriveApplication.getInstance().isAnimShowing()) {
						ShareDriveApplication.getInstance().setAnimIsShowing(
								true);
					}
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation arg0) {
					// TODO Auto-generated method stub
					onBackToParentEnd(final_Pre, finalScr_w, layout);
					if (currentFragment.getDir() == UiConstant.DIR_CODE_1) {
						handler.sendEmptyMessageDelayed(14, 310);
					} else {
						handler.sendEmptyMessageDelayed(13, 310);
					}
					if (ShareDriveApplication.getInstance().isAnimShowing()) {
						ShareDriveApplication.getInstance().setAnimIsShowing(
								false);
					}
					handler.sendEmptyMessageDelayed(UiConstant.ON_ANIMATION_END, 500);
					isTransverseDir = false;
				}
			});
			Log.d("perss", "holder.getPer()[onBackToParent]:" + holder.getPer());
			AlphaAnimation alphaAnim = new AlphaAnimation(holder.getPer(), 0f);
			alphaAnim.setDuration(250);
			layout.setAlpha(1.0f);
			layout.startAnimation(alphaAnim);
			cur.setX(0);
			pre.setX(0);
			pre.startAnimation(pre_Ta);
			cur.startAnimation(cur_Ta);
		}
	}

	private void cancleOnBackToParent(float x) {
		final View cur = (View) getMoveViewMap().get("cur");
		View pre = (View) getMoveViewMap().get("pre");
		final LinearLayout layout = (LinearLayout) getMoveViewMap().get(
				"layout");
		if (null != pre && null != cur && null != layout) {
			DisplayMetrics dm = PublicTools
					.getScreenWidthAndHeight(ShareDriveMainFragmentActivity.this);
			int scr_w = dm.widthPixels;
			final float finalScr_w = scr_w;
			final View final_Pre = pre;
			//
			TranslateAnimation cur_Ta = new TranslateAnimation(cur.getX(),
					-finalScr_w, 0, 0);
			cur_Ta.setDuration(250);
			cur_Ta.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation arg0) {
					// TODO Auto-generated method stub
					// cur.setX(0);
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onAnimationEnd(Animation arg0) {
					// TODO Auto-generated method stub

				}
			});

			TranslateAnimation pre_Ta = new TranslateAnimation(
					final_Pre.getX(), 0, 0, 0);

			pre_Ta.setDuration(250);
			pre_Ta.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation arg0) {
					// TODO Auto-generated method stub
					// final_Pre.setVisibility(View.GONE);
					onBackToParentStart();
					if (!ShareDriveApplication.getInstance().isAnimShowing()) {
						ShareDriveApplication.getInstance().setAnimIsShowing(
								true);
					}
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation arg0) {
					// TODO Auto-generated method stub
					if (View.VISIBLE == layout.getVisibility()) {
						layout.setVisibility(View.GONE);
					}
					ShareDriveApplication.getInstance().setScrolling(false);
					holder.animIsRunning = false;
					if (UiConstant.DIR_CODE_1 == currentFragment.getDir()) {
						handler.sendEmptyMessageDelayed(14, 310);
					}
					if (ShareDriveApplication.getInstance().isAnimShowing()) {
						ShareDriveApplication.getInstance().setAnimIsShowing(
								false);
					}
					isTransverseDir = false;
				}
			});
			float pers = holder.getPer();
			Log.d("perss", "pers[onBackToParent]:" + pers);
			AlphaAnimation alphaAnim = new AlphaAnimation(pers, 1.0f);
			layout.setAlpha(1.0f);
			alphaAnim.setDuration(250);
			layout.startAnimation(alphaAnim);
			pre.setX(0);
			pre.startAnimation(pre_Ta);
			cur.setX(0);
			cur.startAnimation(cur_Ta);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		Log.d("tou12", "ontouch");
		return super.onTouchEvent(event);
	}

	private class Holder {
		private float per = 0f;
		private long oldMills = 0l;
		private boolean islocked = false;
		private long recordMills = 0l;
		private boolean animIsRunning = false;
		private AllFileFragment searchFg;

		public AllFileFragment getSearchFg() {
			return searchFg;
		}

		public void setSearchFg(AllFileFragment searchFg) {
			this.searchFg = searchFg;
		}

		public boolean isIslocked() {
			return islocked;
		}

		public void setIslocked(boolean islocked) {
			this.islocked = islocked;
		}

		public float getPer() {
			return per;
		}

		public void setPer(float per) {
			this.per = per;
		}

	}

	private void onBackToParentEnd(View final_Pre, float finalScr_w,
			LinearLayout layout) {
		ShareDriveApplication.getInstance().setScrolling(false);
		holder.animIsRunning = false;
		final_Pre.setX(finalScr_w);
		if (View.VISIBLE == layout.getVisibility()) {
			layout.setVisibility(View.GONE);
		}
		if (1 < fragmentManager.getBackStackEntryCount()) {
			i_count -= 1;
			fragmentManager.popBackStack();
			currentFragment = (BaseFragment) fragmentManager
					.findFragmentByTag(i_count + "");
			changeTittle(currentFragment.getParent());
		} else if (1 == fragmentManager.getBackStackEntryCount()) {
			i_count = 0;
			switch (currentIndex) {
			case UiConstant.ALLFILEFRAGMENT:
				setTabSelection(UiConstant.ALLFILEFRAGMENT);
				break;
			case UiConstant.SHAREFRAGMENT:
				setTabSelection(UiConstant.SHAREFRAGMENT);
				break;
			default:
				setTabSelection(UiConstant.ALLFILEFRAGMENT);
				break;
			}
		}
	}

	private void onBackToParentStart() {
		holder.animIsRunning = true;
		ShareDriveApplication.getInstance().setAnimIsShowing(true);
	}

	private void searchDismiss() {
		if (null != currentFragment
				&& currentFragment instanceof AllFileFragment) {
			if (UiConstant.DIR_CODE_1 == currentFragment.getDir()) {
				if (null != ((AllFileFragment) currentFragment).getSearchView()) {
					RelativeLayout search_fg_re = ((AllFileFragment) currentFragment)
							.getSearchView();
					if (View.GONE == search_fg_re.getVisibility()) {
						search_fg_re.setVisibility(View.VISIBLE);
						search_fg_re.setClickable(true);
					}
					((AllFileFragment) currentFragment).getAllFileList(1);
					currentFragment.setDir(UiConstant.DIR_CODE_N1);
					if (View.VISIBLE == search_et.getVisibility()) {
						search_et.setVisibility(View.GONE);
					}
				}
				if (View.VISIBLE == frame_tittle_search.getVisibility()) {
					frame_tittle_search.setVisibility(View.GONE);
					if (View.GONE == frame_tittle_all.getVisibility()) {
						frame_tittle_all.setVisibility(View.VISIBLE);
					}
					if (View.VISIBLE == buttom_search_ll.getVisibility()) {
						buttom_search_ll.setVisibility(View.GONE);
					}
					if (View.GONE == buttom_main_ll.getVisibility()) {
						buttom_main_ll.setVisibility(View.VISIBLE);
					}
				}
			}
		}
	}

	private void searchShow() {
		if (null != currentFragment
				&& currentFragment instanceof AllFileFragment) {
			if (UiConstant.DIR_CODE_1 == currentFragment.getDir()) {
				if (null != ((AllFileFragment) currentFragment).getSearchView()) {
					RelativeLayout search_fg_re = ((AllFileFragment) currentFragment)
							.getSearchView();
					if (View.VISIBLE == search_fg_re.getVisibility()) {
						search_fg_re.setVisibility(View.GONE);
						search_fg_re.setClickable(false);
					}
					if (View.GONE == search_et.getVisibility()) {
						search_et.setVisibility(View.VISIBLE);
					}
				}
				if (View.GONE == frame_tittle_search.getVisibility()) {

					search_et.setText("");
					frame_tittle_search.setVisibility(View.VISIBLE);
					if (View.VISIBLE == frame_tittle_all.getVisibility()) {
						frame_tittle_all.setVisibility(View.GONE);
					}
					if (View.GONE == buttom_search_ll.getVisibility()) {
						buttom_search_ll.setVisibility(View.VISIBLE);
					}
					if (View.VISIBLE == buttom_main_ll.getVisibility()) {
						buttom_main_ll.setVisibility(View.GONE);
					}
					PublicTools.showSoftInput(inputManager, search_et);
				}
			}
		}

	}
	
	private ClientExceptionRelateHandler backupHandler = new ClientExceptionRelateHandler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case 2://Upload Success Message
					FileInfo fileInfo = (FileInfo)msg.obj;
					AlbumFileInfo albumFileInfo = new AlbumFileInfo();
					albumFileInfo.setFileName(fileInfo.getName());
					albumFileInfo.setFileSize(fileInfo.getSize());
					albumFileInfo.setClientMtime(fileInfo.getModifiedAt());
					albumFileInfo.setMd5(fileInfo.getMd5());
					DAOFactory.instance(ShareDriveMainFragmentActivity.this).getAlbumDao().insertFile(albumFileInfo );
				default:
					super.handleMessage(msg);
			}
		}

		@Override
		public Context getContext() {
			return ShareDriveMainFragmentActivity.this;
		}
	};
	private Timer backupTimer = null;  
    private TimerTask backupTimerTask = null;  
	
	public void startAlbumBackup(){
		if(backupTimer == null){
			backupTimer = new Timer();
		}
		if(backupTimerTask == null){
			backupTimerTask = new TimerTask() {  
                @Override  
                public void run() {  
                	if(! new WifiController(ShareDriveMainFragmentActivity.this).isWifiConnected()){
                		LogUtil.w(LOG_TAG, "no available wifi");
                		return;
                	}
                	String folderId = new AlbumAction(ShareDriveMainFragmentActivity.this).getAlbumFolderId(
    						shareDriveService, backupHandler);
    				if(folderId != null){
    					File album = new File(ClientConfig.ALBUM_PATH);
    					File[] files = album.listFiles();
    					List<String> paths = new ArrayList<String>();
    					Set<UploadTask> tasks = UploadTaskManager.getAllTaskes();
    					List<String> currentTaskPaths = new ArrayList<String>();
    					for(UploadTask task : tasks){
    						currentTaskPaths.add(task.getFilePath());
    					}
    					IAlbumDao albumDao = DAOFactory.instance(ShareDriveMainFragmentActivity.this).getAlbumDao();
    					for(File file : files){
    						if(!file.isDirectory()){
    							if(albumDao.getFile(file.getAbsolutePath()) != null){
    								continue;
    							}else{
    								String filePath = file.getAbsolutePath();
    								if(!currentTaskPaths.contains(filePath)){
    									paths.add(filePath);
    								}
    								if(paths.size() >= 10){
    									break;
    								}
    							}
    						}
    					}
    					shareDriveService.uploadFile(folderId,paths,null,backupHandler);
    				}else{
    					LogUtil.e(LOG_TAG, "no get available album folder");
    				}
                }  
            };  
		}
		if(backupTimer != null && backupTimerTask != null ){
			backupTimer.schedule(backupTimerTask, 3000, 300000); 
		}
		
	}
	
	public void stopAlbumBackup(){
		if (backupTimer != null) {  
			backupTimer.cancel();  
            backupTimer = null;  
        }  
  
        if (backupTimerTask != null) {  
        	backupTimerTask.cancel();  
        	backupTimerTask = null;  
        }     
	}
}